<template>
    <div>
      <!-- 基础监听示例 -->
      <input v-model="message" placeholder="输入消息" />
      <p>消息变化次数：{{ messageChangeCount }}</p>
  
      <!-- 深度监听示例 -->
      <input v-model="user.name" placeholder="用户名" />
      <input v-model="user.age" type="number" placeholder="年龄" />
  
      <!-- 异步操作示例 -->
      <input v-model="searchQuery" placeholder="搜索关键词" />
      <ul>
        <li v-for="result in searchResults" :key="result">{{ result }}</li>
      </ul>
    </div>
  </template>
  
  <script>
  export default {
    name: "AboutPage",
    data() {
      return {
        message: "",
        messageChangeCount: 0,
        user: {
          name: "Alice",
          age: 25
        },
        searchQuery: "",
        searchResults: []
      };
    },
    watch: {
      // 1. 基础监听：输入框内容变化
      message(newVal, oldVal) {
        this.messageChangeCount++;
        console.log(`消息变化：${oldVal} → ${newVal}`);
      },
  
      // 2. 深度监听对象
      user: {
        handler(newUser) {
          console.log("用户信息更新:", newUser);
        },
        deep: true // 监听对象内部属性变化
      },
  
      // 3. 监听特定属性路径
      "user.name": function(newName) {
        console.log("用户名更新:", newName);
      },
  
      // 4. 带防抖的异步搜索
      searchQuery: {
        handler(newQuery) {
          this.debouncedSearch(newQuery);
        },
        immediate: true // 初始化时执行一次
      }
    },
    created() {
      // 防抖函数初始化
      this.debouncedSearch = this.debounce(this.doSearch, 500);
    },
    methods: {
      // 模拟API请求
      doSearch(query) {
        if (!query) {
          this.searchResults = [];
          return;
        }
        // 模拟异步请求
        setTimeout(() => {
          this.searchResults = [
            `${query} 结果1`,
            `${query} 结果2`,
            `${query} 结果3`
          ];
        }, 300);
      },
  
      // 防抖工具函数
      debounce(fn, delay) {
        let timeoutId;
        return (...args) => {
          clearTimeout(timeoutId);
          timeoutId = setTimeout(() => fn.apply(this, args), delay);
        };
      }
    }
  };
  </script>